package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"path/filepath"
	"store/models"
	"strconv"
	"strings"
)

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}
type StoreController struct {
	beego.Controller
}

// 添加
func (c *StoreController) Add() {
	name := c.GetString("name")
	img := c.GetString("img")
	status := c.GetString("status")
	time := c.GetString("time")
	tel := c.GetString("tel")
	address := c.GetString("address")
	info := c.GetString("info")
	store := models.Store{
		Name:    name,
		Img:     img,
		Status:  status,
		Time:    time,
		Tel:     tel,
		Address: address,
		Info:    info,
	}
	err := models.DB.Model(&models.Store{}).Create(&store).Error
	if name == "" || img == "" || status == "" || time == "" || tel == "" || address == "" || info == "" {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "各个字段不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: store,
		}
		c.ServeJSON()
	}
}

// 上传
func (c *StoreController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "请上传文件",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	if header.Size > 5*1024*1024 {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "文件过大,请重新上传",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	ext := map[string]bool{
		".jpeg": true,
		".png":  true,
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if !ext[suffix] {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "文件类型错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		imgUrl := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "上传成功",
			Data: imgUrl,
		}
		c.ServeJSON()
	}
}

// 列表
func (c *StoreController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 10)
	query := models.DB.Model(&models.Store{})
	pageData := make(map[string]interface{})
	key := "store-" + strconv.Itoa(page)
	val, err := models.Rdb.Get(key).Result()
	if err != nil {
		var count int64
		query.Count(&count)
		var store []models.Store
		offset := (page - 1) * size
		err = query.Offset(offset).Limit(size).Find(&store).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 500,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			pageData["count"] = count
			pageData["store"] = store
			marshal, _ := json.Marshal(&pageData)
			value := string(marshal)
			models.Rdb.Set(key, value, 0)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: pageData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: pageData,
		}
		c.ServeJSON()
	}
}

// 详情
func (c *StoreController) Info() {
	id, _ := c.GetInt("id")
	var store models.Store
	key := "store-" + strconv.Itoa(id)
	val, err := models.Rdb.Get(key).Result()
	RankKey := "duck-rank"

	if err != nil {
		err = models.DB.Where("ID=?", id).First(&store).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 500,
				Msg:  "详情展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {

			marshal, _ := json.Marshal(&store)
			value := string(marshal)
			models.Rdb.Set(key, value, 0)
			models.Rdb.ZIncrBy(RankKey, 1, store.Name)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "详情展示成功-mysql",
				Data: store,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &store)
		models.Rdb.ZIncrBy(RankKey, 1, store.Name)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "详情展示成功-redis",
			Data: store,
		}
		c.ServeJSON()
	}
}

// 删除
func (c *StoreController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Store{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

// 排行榜

func (c *StoreController) Rank() {
	key := "duck-rank"
	nums := models.Rdb.ZCard(key).Val()
	ranks, err := models.Rdb.ZRangeWithScores(key, 0, nums-1).Result()
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "展示成功",
			Data: ranks,
		}
		c.ServeJSON()
	}
}

// 状态修改
func (c *StoreController) Up() {
	id, _ := c.GetInt("id")
	status := c.GetString("status")
	store := models.Store{
		Model:  gorm.Model{ID: uint(id)},
		Status: status,
	}
	err := models.DB.Where("ID=?", id).Updates(&store).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: store,
		}
		c.ServeJSON()
	}
}
